/* eslint-disable  */
import React from 'react';
import { ListView, List, SearchBar, ActivityIndicator } from 'antd-mobile';
import classnames from 'classnames';
import request from '@/utils/request';
import Icon from '../Icon';
import Popup from '../Popup';
import Empty from '../Empty';
import LevelSelect from '../LevelSelect';
import { testJson } from '../LevelSelect/test';
import { itemMaps } from './util';
import './index.less';
const { Item } = List;
export interface IndexListProps {
  required?: boolean;
  textFormat?: (value) => string;
  title: string | React.ReactNode;
  placeholder?: string;
  header?: any;
  data?: any[];
  fetchData?: (current:any, selected:any, value:any) => any;
  value?: { label: string; value: string | number }[];
  // 数据源哪个字段当label
  keyName: 'label';
  // 数据源哪个字段当value
  valueName: 'value';
  cache?: boolean;
  id?: any;

  onChange?: (value) => void;
}

interface State {
  visible: boolean;
}

class Index extends React.Component<IndexListProps, State> {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
    };
  }

  static defaultProps = {
    placeholder: '请选择',
    keyName: 'label',
    valueName: 'value',
  };

  handleClick = () => {
    this.setState({
      visible: true,
    });
  };
  handleOk = (value) => {
    const { onChange } = this.props;
    this.setState({
      visible: false,
    });
    if (typeof onChange === 'function') {
      onChange(value);
    }
  };

  textFormat = (value = []) => {
    const { textFormat } = this.props;
    if (typeof textFormat === 'function') {
      const result = textFormat(value);
      return result ||value;
    }
    return value.map((item) => item.label).join(' - ');
  };
  value2Array = (value) => {
    if (!value) return [];
    if (Array.isArray(value)) return value;
    return [value];
  };
  render() {
    const { visible } = this.state;
    const { required, title, placeholder, value, textFormat, id , data ,fetchData} = this.props;
    return (
      <div className={classnames('hr-level-select')} id={id}>
        <List.Item
          arrow="down"
          extra={
            <div className={classnames('hr-level-select-text', { placeholder: !value })}>
              {!value  ? placeholder : this.textFormat(value)}
            </div>
          }
          onClick={this.handleClick}
        >
          {required && <span className="require-icon">*</span>}
          {title}
        </List.Item>
        <LevelSelect
          visible={visible}
          title={title}
          value={value}
          dataSource={ data}
          fetchData={fetchData}
          onCancel={() => this.setState({ visible: false })}
          onOk={this.handleOk}
        />
      </div>
    );
  }
}

export default Index;
